package com.salts.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.salts.Dao.*;
import com.salts.domain.dto.*;
import com.salts.domain.po.*;
import com.salts.domain.vo.DetailClothVo;
import com.salts.domain.vo.OrderDetailVo;
import com.salts.domain.vo.OrderVo;
import com.salts.domain.vo.UserVo;
import com.salts.service.MineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MineServiceImpl implements MineService {
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    OrderInfoMapper orderInfoMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    ClothMapper clothMapper;
    @Autowired
    StockMapper stockMapper;
    @Override
    public UserVo getUserInfo(UserInfo user) {
        int userId = user.getId();
        UserInfo userInfo = userInfoMapper.selectUserInfo(userId);
        UserVo userVo = new UserVo();
        userVo.setUserName(userInfo.getUserName());
        userVo.setEmail(userInfo.getEmail());
        userVo.setGender(userInfo.getGender());
        userVo.setMobile(userInfo.getMobile());
        userVo.setAvatar(userInfo.getAvatar());
        return userVo;
    }

    @Override
    public List<OrderStateDto> getOrderCount(UserInfo user) throws InvocationTargetException, IllegalAccessException {
        List<OrderStateDto> returnList = new ArrayList<>();
        List<OrderCount> orderCount = orderInfoMapper.getOrderCount(user.getId());
        //复制粘贴术！
        // 创建一个 Map 用于存放不同状态对应的 OrderStateDto
        Map<Integer, OrderStateDto> orderStateDtoMap = new HashMap<>();
        Integer num=0;
        for (OrderCount count : orderCount) {
            OrderStateDto orderStateDto = new OrderStateDto();
            Integer orderstateCount = count.getOrderCount();
            List<Integer> orderState0 = new ArrayList<>(Arrays.asList(0));
            List<Integer> orderState1234 = new ArrayList<>(Arrays.asList(1,2,3,4));
            List<Integer> orderState5 = new ArrayList<>(Arrays.asList(5));
            List<Integer> orderStateCancel = new ArrayList<>(Arrays.asList(-1));
            if (orderState0.contains(count.getOrderState())) {
                String stateName="待付款";
                updateOrderStateDtoMap(orderStateDtoMap, 0, orderstateCount,stateName,orderState0);
            }

            if (orderState1234.contains(count.getOrderState())) {
                String stateName="待配送";
                updateOrderStateDtoMap(orderStateDtoMap, 1234, orderstateCount,stateName,orderState1234);
            }

            if (orderState5.contains(count.getOrderState())) {
                String stateName="待收货";
                updateOrderStateDtoMap(orderStateDtoMap, 5, orderstateCount,stateName,orderState5);
            }

            if (orderStateCancel.contains(count.getOrderState())) {
                String stateName="退款/售后";
                updateOrderStateDtoMap(orderStateDtoMap, -1, orderstateCount,stateName,orderStateCancel);;
            }
        }
        returnList.addAll(orderStateDtoMap.values());
        return returnList;
    }
    private void updateOrderStateDtoMap(Map<Integer, OrderStateDto> orderStateDtoMap, int orderState, int orderstateCount,String stateName,List<Integer> orderStateCancel) {
        // 如果 orderStateDtoMap 中已经存在相应状态的 OrderStateDto，则更新其 orderCount，否则创建新的 OrderStateDto 并添加到 map 中
        if (orderStateDtoMap.containsKey(orderState)) {
            OrderStateDto existingDto = orderStateDtoMap.get(orderState);
            existingDto.setOrderCount(existingDto.getOrderCount() + orderstateCount);
        } else {
            OrderStateDto newDto = new OrderStateDto();
            newDto.setOrderStatusName(stateName);
            newDto.setOrderCount(orderstateCount);
            newDto.setOrderState(orderStateCancel);
            orderStateDtoMap.put(orderState, newDto);
        }
    }

    @Override
    public List<OrderVo> getOrderInfo(GetOrderInfoDto param) {//state: 0全部 1待付款 2待发货 3 待收货 4退款
        Integer state = param.getState();
        String clothName = param.getClothName();
        List<Integer> clothIds = null;
        if (!StringUtils.isEmpty(clothName)){
            List<Cloth> cloth =  clothMapper.queryByName(clothName);
            if (cloth.size()>0){
                clothIds=cloth.stream().map(Cloth::getId).collect(Collectors.toList());
            }
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId",param.getUserId());
        paramMap.put("clothIds",clothIds);
        List<OrderInfo> orderInfos = new ArrayList<>();
        if (state.equals(0)){
            orderInfos=orderInfoMapper.queryMap(paramMap);
        }
        if (state.equals(1)){//0未付款 1已付款+2正在开单+3分拣中+4待配送 5配送中 -1已退款
            paramMap.put("state",0);
            orderInfos=orderInfoMapper.queryMap(paramMap);
        }if(state.equals(2)){
            List<Integer> states = Arrays.asList(1, 2, 3, 4);
            orderInfos=orderInfoMapper.queryListByState(param.getUserId(),states,clothIds);
        }if (state.equals(3)){
            paramMap.put("state",5);
            orderInfos=orderInfoMapper.queryMap(paramMap);
        }if (state.equals(4)){
            paramMap.put("state",-1);
            orderInfos=orderInfoMapper.queryMap(paramMap);
        }
        if (orderInfos.size()==0){
            return null;
        }
        List<Integer> orderIds = orderInfos.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("orderIds",orderIds);
        List<OrderDetail> orderDetails=orderDetailMapper.queryListByMap(queryMap);
        if (orderDetails.size()==0){
            return null;
        }
        Map<Integer, List<OrderDetail>> orderDetailMap = orderDetails.stream().collect(Collectors.groupingBy(OrderDetail::getOrderId));
        List<OrderVo> returnList = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            OrderVo orderVo = new OrderVo();
            List<OrderDetail> orderDetail = orderDetailMap.get(orderInfo.getOrderId());
            orderVo.setOrderInfo(orderInfo);
            orderVo.setOrderDetails(orderDetail);
            returnList.add(orderVo);
        }
        return returnList;
    }

    /**
     * @param orderInfo
     * @return
     */
    @Override
    public OrderDetailVo queryOrderDetail(OrderInfo orderInfo) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        List<Integer> list = Arrays.asList(orderInfo.getOrderId());
        //查询orderInfo
        OrderInfo orderInfoPo = orderInfoMapper.queryList(orderInfo).get(0);
        orderInfoPo.setOrderPayTime(orderInfoPo.getOrderCreateTime());
        //查询orderDetail;
        List<OrderDetail> orderDetailInfo = orderDetailMapper.getOrderDetailInfo(list);
        //查询库存stock;
        List<StockView> stockViews = new ArrayList<>();
        List<DetailClothVo> detailClothVos=new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailInfo) {
            DetailClothVo detailClothVo = new DetailClothVo();


            StockView stockView = new StockView();
            stockView.setClothId(orderDetail.getClothId());
            stockView.setSpec(orderDetail.getSkuSpec());
            stockView.setColor(orderDetail.getSkuColor());
            StockView stockInfo = stockMapper.getStockInfo(stockView);
            stockViews.add(stockInfo);

            detailClothVo.setImgUrl(stockInfo.getImgUrl());
            detailClothVo.setClothName(stockInfo.getClothName());
            detailClothVo.setClothId(stockInfo.getClothId());
            detailClothVo.setColor(stockInfo.getColor());
            detailClothVo.setColorId(stockInfo.getColorId());
            detailClothVo.setSpec(stockInfo.getSpec());
            detailClothVo.setSpecId(stockInfo.getSpecId());
            detailClothVo.setPrice(orderDetail.getSkuPayPrice());
            detailClothVo.setNumber(orderDetail.getPurchaseNum());
            detailClothVo.setDiscountAmount(orderDetail.getDiscountAmount());
            detailClothVo.setPlatformAmount(orderDetail.getPlatformAmount());
            detailClothVo.setShopAmount(orderDetail.getShopAmount());
            detailClothVo.setLogisticsCompany(orderInfoPo.getLogisticsCompany());
            detailClothVo.setLogisticsInfomation(orderInfoPo.getLogisticsInfomation());
            detailClothVo.setCreatTime(orderInfoPo.getOrderCreateTime());
            detailClothVos.add(detailClothVo);
        }
        orderDetailVo.setOrderInfo(orderInfoPo);
        orderDetailVo.setOrderDetails(detailClothVos);
        //拼装
        return orderDetailVo;
    }

    @Override
    public String feedback() {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "{\"qq\":\"2072698911\",\"微信\":\"13811204074\",\"技术负责人\":\"喵吉\"}";

        try {
            // 将JSON字符串转换为对象
            Object jsonObject = objectMapper.readValue(json, Object.class);
            // 将对象转换为字符串并返回
            return objectMapper.writeValueAsString(jsonObject);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // 如果转换过程中出现异常，返回空字符串或者其他错误信息
            return "";
        }
}

    @Override
    public Result updateUserInfo(UserInfo user) {
        Integer result=userInfoMapper.updateUserInfo(user);
        return Result.ok(result>0);
    }

    /**
     * @param orderInfo
     * @return
     */
    @Override
    public LogisticsDto queryLogistics(OrderInfo orderInfo) throws InvocationTargetException, IllegalAccessException {
        List<OrderInfo> orderInfos = orderInfoMapper.queryList(orderInfo);
        OrderInfo info = orderInfos.get(0);
        LogisticsDto logisticsDto = new LogisticsDto();
        logisticsDto.setOrderId(info.getOrderId());
        logisticsDto.setOrderNo(info.getOrderNo());
        logisticsDto.setOrderState(info.getOrderState());
        logisticsDto.setLogisticsCompany(info.getLogisticsCompany());
        logisticsDto.setLogisticsInfomation(info.getLogisticsInfomation());
        return logisticsDto;
    }
}
